package cn.daniellee.plugin.awa.runnable;

import cn.daniellee.plugin.awa.AuthWebApi;
import cn.daniellee.plugin.awa.core.AuthCore;
import cn.daniellee.plugin.awa.model.Auth;
import cn.daniellee.plugin.awa.model.Result;
import com.google.gson.Gson;
import com.sun.net.httpserver.HttpServer;
import fr.xephi.authme.api.v3.AuthMeApi;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class HttpRunnable extends BukkitRunnable {

    @Override
    public void run() {
        try {
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(AuthWebApi.getInstance().getConfig().getInt("setting.socket", 8888)), 0);
            httpServer.createContext("/auth", exchange -> {
                if ("POST".equalsIgnoreCase(exchange.getRequestMethod()) && exchange.getRequestHeaders().getFirst("Content-Type").equals("application/json")) {
                    Auth auth = AuthCore.parseAuth(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
                    if (auth != null) {
                        String password = AuthCore.decryptPassword(auth.getPassword());
                        if (password != null) {
                            Result result = new Result();
                            result.setResult(AuthMeApi.getInstance().checkPassword(auth.getName(), password));
                            String response = new Gson().toJson(result);
                            exchange.sendResponseHeaders(200, 0);
                            OutputStream os = exchange.getResponseBody();
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                            os.close();
                        } else {
                            String response = "Password decrypt failed.";
                            exchange.sendResponseHeaders(400, 0);
                            OutputStream os = exchange.getResponseBody();
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                            os.close();
                        }
                    } else {
                        String response = "Invalid request.";
                        exchange.sendResponseHeaders(400, 0);
                        OutputStream os = exchange.getResponseBody();
                        os.write(response.getBytes(StandardCharsets.UTF_8));
                        os.close();
                    }
                } else {
                    String response = "Request method must be POST, Content-Type must be application/json.";
                    exchange.sendResponseHeaders(403, 0);
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes(StandardCharsets.UTF_8));
                    os.close();
                }
            });
            httpServer.start();
        } catch (IOException e) {
            e.printStackTrace();
            AuthWebApi.getInstance().getLogger().info(" ");
            AuthWebApi.getInstance().getLogger().info("[AuthWebApi]An error occurred while start http server.".replace("&", "§"));
            AuthWebApi.getInstance().getLogger().info(" ");
        }
    }
}
